import { fileURLToPath, URL } from "node:url";
import { resolve } from "node:path";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import VueDevTools from "vite-plugin-vue-devtools";
// ant-design-vue按需加载
import Components from "unplugin-vue-components/vite";
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
// 自动导入
import AutoImport from "unplugin-auto-import/vite";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
//  gzip构建压缩
import compression from "vite-plugin-compression";
// 生成包大小的可视化报告
import { visualizer } from "rollup-plugin-visualizer";
// 构建进度显示
import progress from "vite-plugin-progress";
// 用户侧版本显示
import { execSync } from "node:child_process";

const now = new Date().toLocaleString("zh-CN");
const hash = execSync("git rev-parse --short HEAD").toString().trim();

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  return {
    define: {
      __BUILD_INFO__: JSON.stringify({ version: hash, time: now }),
    },
    base: mode === "production" ? "/admin/" : "/",
    resolve: {
      // 导入时想要省略的扩展名列表
      // 默认： ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
      extensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    plugins: [
      vue(),
      VueDevTools(),
      visualizer({ open: true, gzipSize: true, brotliSize: true, template: "treemap" }),
      createSvgIconsPlugin({
        iconDirs: [resolve("src/assets/icons")], // 你的图标目录
        symbolId: "icon-[name]",
      }),
      AutoImport({
        imports: ["vue", "vue-router", "pinia"], // 预设
        dts: "src/types/auto-imports.d.ts", // 生成类型
        eslintrc: { enabled: true }, // 同步 ESLint
      }),
      Components({
        dts: "src/types/components.d.ts",
        resolvers: [
          AntDesignVueResolver({
            importStyle: false, // 是否自动导入样式，根据你的需求
          }),
        ],
      }),
      // gzip 压缩
      compression({
        algorithm: "gzip",
        ext: ".gz",
        threshold: 10240, // ≥ 10 KiB 才压缩
        deleteOriginFile: false, // 保留源文件，让 Nginx 按协商返回
      }),
      // Brotli 压缩（现代浏览器优先）
      compression({
        algorithm: "brotliCompress",
        ext: ".br",
        threshold: 10240,
        deleteOriginFile: false,
      }),
      progress({
        format: "构建进度 [:bar] :percent :current/:total",
        total: 100,
        width: 40,
        complete: "█",
        incomplete: "░",
      }),
    ],
    build: {
      // 超过1500kb则会告警
      chunkSizeWarningLimit: 1500,
      // 开启 JS / CSS 代码压缩（esbuild 已内置）
      minify: "esbuild",
      cssCodeSplit: true, // 单独抽离 CSS
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes("node_modules")) {
              if (id.includes("vue")) {
                return "vue";
              } else if (["vue-router", "pinia"].some(pkg => id.includes(pkg))) {
                return "vue-router_pinia";
              } else if (["axios"].some(pkg => id.includes(pkg))) {
                return "axios";
              } else if (id.includes("ant-design-vue")) {
                return "ant-design-vue";
              } else {
                return "vender";
              }
            }
          },
          // 定义入口 chunk 文件的命名格式
          entryFileNames: `assets/[name]-[hash].js`,
          // 定义生成的 chunk 文件的命名格式（除了入口 chunk 和动态导入的 chunk 外)
          chunkFileNames: `assets/[name]-[hash].js`,
          // 定义静态资源文件（如 CSS、图片、字体等）的命名格式。
          assetFileNames: `assets/[name]-[hash].[ext]`,
        },
      },
    },
    server: {
      // https: true,
      proxy: {
        "/zc-api": {
          target: "https://zc-smart-test.sci-brain.cn",
          changeOrigin: true,
          rewrite: path => {
            return path.replace(/\/zc-api/, "/api");
          },
        },
        "/ws-api": {
          target: "https://chatbi-test.sci-brain.cn",
          changeOrigin: true,
          rewrite: path => {
            return path.replace(/\/ws-api/, "/api");
          },
        },
        "/api": {
          target: "http://localhost:5173", // 占位即可
          changeOrigin: true,
          //   bypass: (req, _res) => {
          //     if (req.url?.startsWith("/api/")) {
          //       return JSON.stringify({ code: 200, data: { msg: "mock ok" } });
          //     }
          //   },
        },
      },
    },
  };
});
